package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        log.info(requestURI);
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend",
                "/front",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars",
                "/swagger-resources",
                "/v2/api-docs"};
        for (String url : urls) {
            if (requestURI.contains(url)){
                filterChain.doFilter(request,response);
                return;
            }
            /*boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                filterChain.doFilter(request,response);
            }*/
        }

        HttpSession session = request.getSession();
        //判断用户是否登录
        Long userId = (Long) session.getAttribute("userId");
        if (userId != null){
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request,response);
            return;
        }
        //判断员工是否登录
        Object emp = session.getAttribute("emp");
        if (emp != null){
            filterChain.doFilter(request,response);
            return;
        }
        String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(jsonString);
    }
}
